#Nature's Kidneys: the Role of Wetland Reserve Easements in Restoring Water Quality
#Nicole Karwowski and Marin Skidmore
#Replication File
#2025

#Open Rivers and Streams SF
#find distance to nearest stream/river for each huc 12

##open packages
#load libraries
library(ggplot2)
library(raster)
library(sf)
library(exactextractr)
library(prism)
library(Rcpp)
library(data.table)
library(tidyverse)
library(Hmisc)
library(haven)
library(stargazer)
library(purrr)
library(tidyr)
library(lwgeom)
library(collapse)
library(ggthemes)
library(scales)
library(tigris)
options(tigris_use_cache = TRUE)
library(mapview)
options(scipen=999)
library(stringr)
library(data.table)
library(lubridate)
library(units)
library(geosphere)
library(sp)
library(nngeo)

#set wd
setwd("C:/Users/16308/OneDrive - Montana State University/UW_Madison/Water quality/Replication Package")

#open marb sf
MARB<-st_read("Data/WatershedBoundaries/Processed/MARB/MARB.shp")

#open rivers and streams sf 
rivers<-st_read("Data/Rivers_Streams/Raw/USA_Rivers_and_Streams/USA_Rivers_and_Streams.shp")

#make same crs
crs(MARB)
rivers<-st_transform(rivers, crs=st_crs(MARB))
crs(rivers)


#look into the rivers db
table(rivers$Feature)


#identify nearest feature
nearest<-st_nearest_feature(MARB, rivers, progress=TRUE)

#get distance between them
dist<-st_distance(MARB, rivers[nearest,], by_element=TRUE)

#bind
join<-cbind(MARB, st_drop_geometry(rivers)[nearest,])

join$distance=dist

#keep certain variables
join<-subset(join, select=c(huc12, OBJECTID, Name, Feature, Miles, distance))
join<-st_drop_geometry(join)

summary(join)
table(join$Feature)

#save
river_nearest_huc12<-join
save(river_nearest_huc12, file="Data/Rivers_Streams/Processed/nn_rivers_huc12.RData")
